import React, {useEffect, useState} from 'react'
import { Form, Button, DatePicker,Upload,Input, Modal,Row,message, Col,Popconfirm,Select,Descriptions} from 'antd'
import { connect } from 'umi'
import moment from 'moment'
import {UploadOutlined} from '@ant-design/icons';
import {getUploadUrl} from '@/utils/upload'
import {jobLevelTypeList} from "@/utils/constant"
import store from 'store2';

const FormItem = Form.Item;
const { TextArea } = Input;
const {Option} = Select

const formLayout = {
  labelCol: { span: 7 },
};

const colStyle = {
  xl: 8,
  lg: 8,
  md: 8,
  sm: 8,
  xs: 8,
};

let uploadedFiles = [];

const SettlementForm = (props) => {
  const { onSubmit, onCancel, loading,visible,global = {},record } = props;
  const {options = {}} = global;
  const {jobLevel = []} = options;
  const [form] = Form.useForm();
  const [fileUploadUrls,setFileUploadUrls] = useState([]);
  const [fileName, setFileName] = useState(null);

  const fileList = {
    name: 'file',
    multiple: true,
    action: getUploadUrl(),
    defaultFileList: uploadedFiles,
    data: {name: fileName},
    beforeUpload(file) {
      setFileName(file.name)
    },
    onChange(res) {
      const {status} = res.file;
      if (status === 'done') {
        if (res.file.response.error) {
          message.success(`${res.file.response.error}`);
        } else {
          setFileUploadUrls([...fileUploadUrls,res.file.response ]);
          message.success(`${res.file.name} 文件上传成功`);
        }
      } else if (status === 'error') {
        message.error(`${res.file.name} 文件上传失败`);
      }
    },
    onRemove(info) {
      let urls = fileUploadUrls;
      let index = urls.indexOf(info.response);
      if (index > -1)
        urls.splice(index, 1);
      setFileUploadUrls(urls);
    }
  };

  useEffect(() => {
    if(record){
      const fieldsValue = store(`personnel-resign-settlement-` + record.id);
      if(fieldsValue && visible){
        form.setFieldsValue({...fieldsValue,applyTime:moment(fieldsValue.applyTime),hiredate:moment(fieldsValue.hiredate),dimissionTime:moment(fieldsValue.dimissionTime)});
        let temp = [];
        fieldsValue.urlIds.fileList?.map(item => {temp.push(item.response);});
        setFileUploadUrls(temp);
        uploadedFiles = fieldsValue.urlIds.fileList;
      }else {
        form.setFieldsValue({
          ...record,
          hiredate: record.hiredate ? moment(record.hiredate) : undefined,
          applyTime: moment(),
          dimissionTime: record.dimissionTime ? moment(record.dimissionTime) : undefined,
          remark: ''
        });
      }
    }
  }, [visible]);

  const onFormCancel = () => {
    form.resetFields();
    uploadedFiles = [];
    setFileUploadUrls([]);
    onCancel();
  };

  const handleSubmit = async () => {
    const fieldsValue = await form.validateFields();
    form.resetFields();
    onSubmit({...record,...fieldsValue,urlIdsList:fileUploadUrls,urlIds:'',applyCode:record.code});
    uploadedFiles = [];
    setFileUploadUrls([]);
  };

  const onFormSave = async () => {
    const fieldsValue = await form.getFieldsValue();
    store(`personnel-resign-settlement-` + record.id,fieldsValue);
    message.success("信息暂存成功！");
  };

  const renderContent = () => {
    return (
      <>
        <Row gutter={24}>
          <Col {...colStyle}>
            <FormItem name="name" label="申请人">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="applyTime" label="申请日期">
              <DatePicker disabled={true} className='widthStyle'/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="code" label="员工工号">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="hiredate" label="入职日期">
              <DatePicker disabled={true} className='widthStyle'/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="unitname" label="所属部门">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="jobname" label="任职岗位">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="jobLevelType" label="职级类型">
              <Select disabled={true}>
                {jobLevelTypeList.map((item, index) => {
                  return (
                    <Option value={item.value} key={item.value}>
                      {item.label}
                    </Option>
                  )
                })}
              </Select>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="jobLevelId" label="职级">
              <Select disabled={true}>
                {
                  jobLevel.map((item, index) => {
                    return (
                      <Option value={item.id} key={item.name}>
                        {item.name}
                      </Option>
                    )
                  })
                }
              </Select>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="dimissionTime" label="离职日期" rules={[{required: true, message: '离职日期不能为空'}]}>
              <DatePicker disabled={true} className='widthStyle'/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem label='身份证' name="idcard"  rules={[{required: true, message: '身份证号码不能为空'}]}>
              <Input placeholder="请输入身份证号码"/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="associate" label="工作接收人" rules={[{required: true, message: '工作接收人不能为空'}]}>
              <Input disabled={true} placeholder="请输入工作交接人"/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="urlIds" label="上传附件">
              <Upload {...fileList}>
                <Button>
                  <UploadOutlined/> 点击上传附件
                </Button>
              </Upload>
            </FormItem>
          </Col>
          <Col span={24}>
            <FormItem name="remark" labelCol={{span: 2}} label="备注">
              <TextArea rows={4} className='widthStyle'/>
            </FormItem>
          </Col>
          <Col span={24}>
            <FormItem>
              <Descriptions bordered={true}>
                <Descriptions.Item>本人离职时，已将所有属于公司财产、物品、资料归还给公司，并与公司不再有任何劳动和用工的纠纷
                  ，工作移交未有任何隐瞒。本人承诺，无论本人基于何种原因离职，从离职日期起仍承担与任职期间一样的保密义务，保守公司商业机密，
                  直至到该秘密信息被公司公开或为公众所知之日。如本人违反保密义务，侵犯公司的秘密信息，公司将有权依法追究本人的法律和经济责任！</Descriptions.Item>
              </Descriptions>
            </FormItem>
          </Col>
        </Row>
      </>
    )
  };

  const renderFooter = () => {
    return (
      <>
        <Button onClick={() => onFormCancel()}>取消</Button>
        <Button onClick={() => onFormSave()}>暂存</Button>
        <Popconfirm title={`是否确认发起离职结算?`}
                    onConfirm={() => handleSubmit()}
                    okText="是"
                    cancelText="否">
          <Button type="primary" loading={loading}>提交</Button>
        </Popconfirm>
      </>
    )
  };

  return (
    <Modal
      maskClosable={false}
      width={1280}
      destroyOnClose
      centered
      title="离职结算"
      visible={visible}
      footer={renderFooter()}
      onOk={handleSubmit}
      onCancel={() => onFormCancel()}
      onClose={() => onFormCancel()}
      okText="确认"
      cancelText="取消"
    >
      <Form
        {...formLayout}
        form={form}
        style={{ paddingTop: '24px' }}
      >
        {renderContent()}
      </Form>
    </Modal>
  )
}

export default connect(({global,user}) => ({
  currentUser: user.currentUser,
  global
}))(SettlementForm)
